package com.naiterui.ehp.bs.cms.modules.pharmacy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.cms.common.vo.PageParamsVO;
import com.naiterui.ehp.bs.cms.common.vo.PageVO;
import com.naiterui.ehp.bs.cms.modules.pharmacy.entity.Warehouse;
import com.naiterui.ehp.bs.cms.modules.pharmacy.feign.DsWarehouseFeignClient;
import com.naiterui.ehp.bs.cms.modules.pharmacy.mapper.WarehouseMapper;
import com.naiterui.ehp.bs.cms.modules.pharmacy.service.IWarehouseService;
import com.naiterui.ehp.bs.cms.modules.pharmacy.vo.WarehouseManageVO;
import com.naiterui.ehp.bs.cms.modules.pharmacy.vo.WarehouseSelectVO;
import com.naiterui.ehp.bs.cms.modules.pharmacy.vo.WarehouseVO;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements IWarehouseService {

  @Autowired
  private DsWarehouseFeignClient dsWarehouseFeignClient;

  @Override
  public PageVO<WarehouseVO> queryPage(PageParamsVO pageParamsVO, WarehouseVO warehouse) {
    QueryWrapper<WarehouseVO> entityWrapper = this.buildEntityWrapper(pageParamsVO, warehouse);
    IPage<WarehouseVO> page = this.baseMapper.getPage(pageParamsVO.getPage(), entityWrapper);
    List<WarehouseVO> records = page.getRecords();
    records.forEach(record -> {
      Long warehouseId = record.getId();
      String userName = null;
      try {
        userName = this.dsWarehouseFeignClient.getUserName(warehouseId);
      } catch (BusinessException e) {
        this.log.error(e.getMessage(), e);
      }
      WarehouseManageVO manageVO = new WarehouseManageVO();
      manageVO.setUserName(userName);
      record.setManage(manageVO);
    });
    return PageVO.toPageVo(page);
  }

  private QueryWrapper<WarehouseVO> buildEntityWrapper(PageParamsVO pageParamsVO, WarehouseVO warehouse) {

    QueryWrapper<WarehouseVO> entityWrapper = pageParamsVO.getEntityWrapper("t");

    String code = warehouse.getCode();
    entityWrapper.eq(StringUtils.isNotBlank(code), "t.code", code);

    String name = warehouse.getName();
    entityWrapper.like(StringUtils.isNotBlank(name), "t.name", name);

    return entityWrapper;
  }

  @Override
  public List<WarehouseSelectVO> getSelectList() {
    return this.baseMapper.getSelectList();
  }

}
